<template>
  <!-- 文件平铺 -->
  <div class="file_grid_wrapper" @scroll="handleScroll">
    <ul class="file_list" v-loading="loading" element-loading-text="文件加载中...">

      <li class="file_item"
          v-for="(item,index) in dataList"
          :key="index"
          :class="item.checked?'checked':''"
          :title="item.name"
          @contextmenu.prevent="handleContextMenu($event,index)"
          @click="ClickItem(item,index)"
          @dblclick="fileClick(item)"
      >
        <div>
          <div v-if="item.fileType==3" class="videoContent">
            <img class="video_img" src="@/assets/images/video_img.png" alt="加载失败">
            <video-review class="video_box" :ref="`videoReview-${index}`" :videoSrc="item.url"></video-review>
          </div>
          <div style="width: 60px;height: 60px;margin: auto" v-else>
            <img src="@/assets/image_library/dirlarge.png" v-if="item.isDir==1" :style="`height:60px; width:60px;`"/>
            <el-image
              class="file-img"
              :src="item.url"
              :style="`height:60px; width:60px;`"
              fit="cover"
              v-else-if="item.fileType==4"
            />
            <el-image
              class="file-img"
              :src="FileImage[item.extendName]? FileImage[item.extendName]:require('@/assets/image_library/neticon.png')"
              :style="`height:50px; width:50px`"
              fit="cover"
              v-if="item.fileType!=4&&item.fileType!=3&&item.isDir!=1"
            />
          </div>
        </div>
        <el-tooltip class="item" effect="dark" :content="item.fileName" placement="top-end" v-if="!item.reSetName&&item.isDir">
          <div
            class="file-name"
          >{{ item.fileName }}
          </div>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="`${ item.fileName }.${item.extendName }`" placement="top-end"
                    v-if="!item.reSetName&&!item.isDir"
        >
          <div
            class="file-name"
          >{{ item.fileName }}.{{ item.extendName }}
          </div>
        </el-tooltip>
        <el-input v-model="item.fileName" v-if="item.reSetName" @input="checkFileName(value,index)"
                  @blur="saveName(item,index)" :ref="`input_${index}`"
        ></el-input>
        <div
          :class="item.checked?'file-checked-wrapper checked':'file-checked-wrapper'"
        >
          <div class="item_top">
            <div @click.stop>
              <el-checkbox
                class="file-checked"
                v-model="item.checked"
                @change="checkChange"
              />
            </div>
            <div @click.stop>
              <el-dropdown trigger="click" placement="bottom-start" @command="handleCommand" :ref="`moreBtns_${index}`">
               <span class="moreBtns">
                 <i class="el-icon-more"></i>
               </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{...item,type:'open',index:index}">
                    <i class="el-icon-zoom-in"></i>
                    打开
                  </el-dropdown-item>
                  <el-dropdown-item :command="{...item,type:'openParent',index:index}"
                                    v-if="(fileType!=0||search_text!='')&&map=='library'"
                  >
                    <i class="el-icon-folder-opened"></i>
                    打开所属文件夹
                  </el-dropdown-item>
                  <el-dropdown-item :command="{...item,type:'downLoad'}" v-if="item.isDir!=1">
                    <i class="el-icon-download"></i>
                    下载
                  </el-dropdown-item>
                  <el-dropdown-item :command="{...item,type:'copy'}" v-if="map==='library'">
                    <i class="el-icon-document-copy"></i>
                    复制到
                  </el-dropdown-item>
                  <el-dropdown-item :command="{...item,type:'librarycopy'}"
                                    v-if="map!='library'&&(!isAdmin&&!isGroupowner)"
                  >
                    <i class="el-icon-document-copy"></i>
                    复制到
                  </el-dropdown-item>
                  <el-dropdown trigger="hover" placement="bottom-end" v-if="map!='library'&&(isAdmin||isGroupowner)"
                               @command="handelCopy" style="width: 100%;"
                  >
                    <el-dropdown-item>
                      <i class="el-icon-document-copy"></i>
                      复制到
                      <i class="el-icon-arrow-right"></i>
                    </el-dropdown-item>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="{...item,map:1}">群文件</el-dropdown-item>
                      <el-dropdown-item :command="{...item,map:2}">我的文件</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>

                  <el-dropdown-item :command="{...item,type:'move'}" v-if="map=='library'||(isAdmin||isGroupowner)">
                    <i class="el-icon-folder-add"></i>
                    移动到
                  </el-dropdown-item>
                  <el-dropdown-item :command="{...item,type:'resetName',index:index}"
                                    v-if="map=='library'||(isAdmin||isGroupowner)"
                  >
                    <i class="el-icon-edit-outline"></i>
                    重命名
                  </el-dropdown-item>
                  <el-dropdown-item :command="{...item,type:'detail'}">
                    <i class="el-icon-warning-outline"></i>
                    详细信息
                  </el-dropdown-item>
                  <el-dropdown-item :command="{...item,type:'delete'}" v-if="map=='library'||(isAdmin||isGroupowner)">
                    <i class="el-icon-delete"></i>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </div>
      </li>
    </ul>

    <!--    详细信息-->
    <DetailMsg ref="detailmsg"></DetailMsg>
    <!--    移动复制-->
    <MoveDialog ref="moveDialog" @uploadNew="uploadNewFile"></MoveDialog>
    <fileDrawer
      :show.sync="drawer"
      :url="drawerurl"
      :name="drawername"
      :type="drawertype"
    ></fileDrawer>
    <AudioDialog ref="audioDialog"></AudioDialog>
  </div>
</template>

<script>
import AudioDialog from '@/views/library_homePage/component/audioDialog.vue'
import videoReview from '@/views/library_homePage/component/videoReview.vue'
import DetailMsg from '@/views/library_homePage/component/DetailMsg.vue'
import MoveDialog from '@/views/library_homePage/component/moveDialog.vue'
import {
  renameFile,
  batchDeleteFile,
  createFolder,
  getFileParentPathList
} from '@/api/library_index'
import fileDrawer from '@/components/fileDrawer.vue'
import { mapGetters, mapMutations } from 'vuex'
import { GroupbatchDeleteFile, GroupcreateFolder, GrouprenameFile } from '@/api/library_groupList/groupList'
import { savedownloadFile } from '@/api/library_filrList/fileList'
import { saveAs } from 'file-saver'

export default {
  name: 'FileList',
  components: { videoReview, DetailMsg, MoveDialog, fileDrawer, AudioDialog },
  model: {
    prop: 'value',
    event: 'update:value'
  },
  props: {
    // 文件类型
    fileType: {
      required: true,
      type: Number
    },
    search_text: {
      type: String
    },
    fileList: Array,//  文件列表
    value: {
      type: Boolean,
      default: false
    },
    map: String,
    groupId: Number,
    isAdmin: {
      type: [Boolean, String]
    },
    isGroupowner: {
      type: [Boolean, String]
    }
  },
  watch: {
    fileList: {
      handler(val) {
        if (val && Array.isArray(val) && val.length > 0) {
          let arr = JSON.parse(JSON.stringify(val))
          this.dataList = arr.map(item => {
            return {
              ...item,
              checked: false,
              oldName: item.fileName,
              reSetName: item.reSetName ? item.reSetName : false
            }
          })
          let activeIndex = arr.findIndex(item => item.reSetName)
          if (activeIndex != -1) {
            this.$nextTick(() => {
              this.$refs[`input_${activeIndex}`][0].focus()
            })
            this.$forceUpdate()
          }
        }
      },
      deep: true,
      immediate: true
    },
    value: {
      handler(val) {
        this.checkAllChange(val)
      }
    }
  },
  data() {
    return {
      loading: false,
      dataList: [],
      fileListSorted: [],
      selectedFile: {},
      drawer: false,
      drawerurl: '',
      drawername: '',
      drawertype: '',
      typeList: [],
      FileImage: {
        'pdf': require('@/assets/image_library/pdficon.png'),
        'docx': require('@/assets/image_library/wordIcon.png'),
        'dov': require('@/assets/image_library/wordIcon.png'),
        'xls': require('@/assets/image_library/excelicon.png'),
        'xlsx': require('@/assets/image_library/excelicon.png'),
        'ppt': require('@/assets/image_library/ppticon.png'),
        'pptx': require('@/assets/image_library/ppticon.png'),
        'txt': require('@/assets/image_library/texticon.png'),
        'zip': require('@/assets/image_library/zipicon.png'),
        'rar': require('@/assets/image_library/zipicon.png'),
        'mp3': require('@/assets/image_library/musicicon.png')
      },
      clickTimeout: null

    }
  },
  computed: {
    ...mapGetters('libraryFile', ['pathArr']),
    isCheckAll() {
      return this.dataList.filter(item => item.checked).length === this.dataList.length
    }
  },
  methods: {
    ...mapMutations('libraryFile', ['removePath', 'clearPathArr', 'addPath', 'changePathArr']),
    uploadNewFile() {
      if (this.map === 'group') {
        this.$parent.getFilesList(this.pathArr[this.pathArr.length - 1].id, this.groupId)
      } else {
        this.$parent.getFilesList(this.pathArr[this.pathArr.length - 1].id)
      }

    },
    handleScroll(event) {
      const { scrollTop, clientHeight, scrollHeight } = event.target
      if (scrollTop + clientHeight >= scrollHeight) {
        // 滚动条到达底部，触发懒加载
        this.loadMoreData()
      }
    },
    loadMoreData() {
      this.$emit('lookMore')
    },
    handleCommand(command) {
      switch (command.type) {
        case 'resetName':
          this.dataList[command.index].reSetName = true
          this.$nextTick(() => {
            this.$refs[`input_${command.index}`][0].focus()
          })
          this.$emit('isEdit', { isEdit: true })
          this.$forceUpdate()
          break
        case 'detail':
          this.$refs.detailmsg.show(command, this.map)
          break
        case 'move':
          if (this.map === 'group') {
            this.$refs.moveDialog.show('move', [command.id], [command.fileName], 1, this.groupId)
          } else {
            this.$refs.moveDialog.show('move', [command.id], [command.fileName])
          }
          break
        case 'copy':
          this.$refs.moveDialog.show('copy', [command.id], [command.fileName])
          break
        case 'librarycopy':
          this.$refs.moveDialog.show('copy', [command.id], [command.fileName], 2, this.groupId)
          break
        case 'delete':
          this.deletefile(command)
          break

        case 'open':
          this.fileClick(command)
          break
        case 'downLoad':
          this.saveLocal(command)
          break
        case 'openParent':
          this.$emit('openfileParent', { id: command.parentId })
          this.getparentPath(command.id)

          break
      }
    },
    // 获取文件所有父路径
    async getparentPath(id) {
      let res = await getFileParentPathList(id)
      if (res.code == 200) {
        let arr = []
        if (res.data && res.data.length > 0) {
          res.data.forEach((item, index) => {
            const keys = Object.keys(item)
            const values = Object.values(item)
            arr.push({ filePath: index === 0 ? '/' : index === 1 ? keys[0] : '/' + keys[0], id: values[0], fileName: keys[0] })
          })
        }
        // TODO:打开所属文件夹
        this.changePathArr(arr)
      }
    },
    async handleSave(command) {
      await saveAs(command.url, command.fileName + '.' + command.extendName)
    },
    async saveLocal(command) {
      await this.handleSave(command)
      if (this.map == 'group') {
        this.saveDownload(command.fileName, command.extendName, command.filePath, command.id, command.size, this.groupId)
      } else {
        this.saveDownload(command.fileName, command.extendName, command.filePath, command.id, command.size)
      }
    },
    // 复制
    handelCopy(command) {
      this.$refs.moveDialog.show('copy', [command.id], [command.fileName], command.map, this.groupId)
    },
    checkFileName(value, index) {
      this.dataList[index].fileName = this.dataList[index].fileName.replace(/[\\/:：*?"“”？<>|]/g, '')
      if (this.dataList[index].fileName.length > 100) {
        this.dataList[index].fileName = this.dataList[index].fileName.slice(0, 100)
      }
    },

    handleContextMenu(event, index) {
      event.preventDefault()
      setTimeout(() => {
        this.$refs[`moreBtns_${index}`][0].show()
      }, 400)
    },
    // 重命名
    async saveName(item, index) {
      if (item.fileName === item.oldName && item.fileName != '新建文件夹') {
        this.dataList[index].reSetName = false
        return
      }
      if (item.parentId != undefined) {
        if (this.map === 'library') {
          this.ResetNameDir(item.id, item.fileName)
        } else if (this.map === 'group') {
          this.ResetGroupDirName(item.id, item.fileName)
        }
        this.$emit('isEdit', { isEdit: false })
      } else {
        let filePath = `${this.pathArr[this.pathArr.length - 1].filePath}${this.pathArr[this.pathArr.length - 1].filePath == '/' ? '' : '/'}${this.pathArr[this.pathArr.length - 1].fileName || ''}`
        let parentId = this.pathArr[this.pathArr.length - 1].id
        if (this.map === 'library') {
          this.buildlibraryDir(item.fileName, filePath, parentId)
        } else if (this.map === 'group') {
          this.buildGroupDir(item.fileName, filePath, parentId)
        }
      }
      this.dataList[index].reSetName = false

    },
    // 删除
    deletefile(item) {
      this.$confirm(`${this.map === 'group' ? '确定删除选择文件吗？' : '确定删除已选择文件吗？删除后，可在回收站找回已删除文件'}`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        if (this.map === 'library') {
          this.DeleteLibraryFile(item.id, item.parentId)
        } else if (this.map === 'group') {
          this.DeleteGroupFile(item.id, item.parentId)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    checkChange() {
      this.$emit('checklist', { arr: this.dataList.filter(item => item.checked) })
      if (this.isCheckAll) {
        this.$emit('update:value', true)

      } else if (this.dataList.filter(item => item.checked).length === 0) {
        this.$emit('update:value', false)
      }
    },
    ClickItem(item, index) {
      // 清除之前的定时器
      clearTimeout(this.clickTimeout)

      // 设置一个新的定时器来延迟单击事件的触发
      this.clickTimeout = setTimeout(() => {
        this.dataList[index].checked = !this.dataList[index].checked
        this.checkChange()
        // 在这里处理单击事件
      }, 200) // 200ms 的延迟时间

    },
    // 全选
    checkAllChange(val) {
      this.dataList.forEach(item => {
        item.checked = val
      })
      this.$emit('checklist', { arr: this.dataList.filter(item => item.checked) })
    },
    /**
     * 文件点击事件
     * @param item
     */
    fileClick(item) {
      if (item.reSetName) {
        return
      }
      // 清除定时器以防止单击事件触发
      clearTimeout(this.clickTimeout)
      if (item.isDir === 1) {
        this.$emit('nextInto', { id: item.id })
        this.addPath(item)
        // 如果是文件夹则进入下一级
      } else {
        this.lookFiles(item.url, item.fileName)
      }
    },
    lookFiles(url, name) {
      let uploadType = url.slice(url.lastIndexOf('.'), url.length).toLowerCase()
      let arr = [
        '.gif',
        '.png',
        '.jpeg',
        '.jpg',
        '.mp4',
        '.webm',
        '.pdf',
        '.wps',
        '.docx',
        '.doc',
        '.rtf',
        '.pptx',
        '.ppt',
        '.xls',
        '.xlsx',
        '.wps',
        '.ofd',
        '.txt',
        '.js',
        '.json',
        '.css',
        '.sql',
        '.xml',
        '.java',
        '.cs(c#)'
      ]
      if (arr.indexOf(uploadType) > -1) {
        this.drawer = true
        this.drawerurl = url
        this.drawername = name
        this.drawertype = 1
      } else if (uploadType == '.mp3') {
        window.open(url, '_blank')
      } else {
        this.$message.info('暂不支持在线预览，请下载后查看')
      }
    },
    // 新建资源库文件夹
    async buildlibraryDir(fileName, filePath, parentId) {
      let res = await createFolder({ fileName: fileName, filePath: filePath, parentId: parentId })
      if (res.code == 200) {
        this.$message.success('新建成功')
        this.$emit('nextInto', { id: this.pathArr[this.pathArr.length - 1].id })
      }
    },
    // 新建群组文件夹
    async buildGroupDir(fileName, filePath, parentId) {
      let res = await GroupcreateFolder({
        groupId: this.groupId,
        fileName: fileName,
        filePath: filePath,
        parentId: parentId
      })
      if (res.code == 200) {
        this.$message.success('新建成功')
        this.$emit('nextInto', { id: this.pathArr[this.pathArr.length - 1].id })
      }
    },
    // 资源库文件重命名
    async ResetNameDir(id, fileName) {
      let res = await renameFile({ id: id, fileName: fileName })
      if (res.code == 200) {
        this.$message.success('命名成功')
      }
    },
    // 群组文件重命名
    async ResetGroupDirName(id, fileName) {
      let res = await GrouprenameFile({ id: id, fileName: fileName, groupId: this.groupId })
      if (res.code == 200) {
        this.$message.success('命名成功')
      }

    },
    // 资源库删除
    async DeleteLibraryFile(id, parentId) {
      let res = await batchDeleteFile({ userId: this.$store.getters.userId, ids: [id].join(',') })
      if (res.code == 200) {
        this.$emit('nextInto', { id: parentId })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }
    },
    // 群文件删除
    async DeleteGroupFile(id, parentId) {
      let res = await GroupbatchDeleteFile({ groupId: this.groupId, ids: [id].join(',') })
      if (res.code == 200) {
        this.$emit('nextInto', { id: parentId })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }
    },
    // 记录下载文件
    async saveDownload(fileName, extendName, filePath, fileId, fileSize, groupId) {
      let obj = {
        fileName,
        extendName,
        filePath,
        groupId: groupId || '',
        fileId,
        fileSize
      }
      await savedownloadFile(obj)
    }
  }
}

</script>


<style scoped lang="scss">
::v-deep .el-input--medium .el-input__inner {
  height: 26px !important;
  text-align: center !important;
}

.file_grid_wrapper {
  padding: 10px;
  box-sizing: border-box;
  height: 100%;
  overflow-y: scroll;

  .file_list {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    align-content: flex-start;
    list-style: none;

    .file_item {
      width: 130px;
      height: 120px;
      margin: 0 16px 16px 0;
      position: relative;
      padding: 25px 16px 8px 16px;
      box-sizing: border-box;
      text-align: center;
      cursor: pointer;
      z-index: 1;
      border-radius: 10px;

      .videoContent {
        position: relative;
        height: 60px;
        width: 60px;
        left: 50%;
        transform: translateX(-50%);

        .video_img {
          width: 24px;
          height: 24px;
          object-fit: cover;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }

        .video_box {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #f5f5f5;
          border-radius: 8px;
          cursor: pointer;

        }
      }

      &:hover {
        background: rgba(245, 247, 250, 0.5);

        .file-checked-wrapper {
          position: absolute;
          z-index: -1;
          display: block;
        }
      }

      .file-name {
        margin-top: 8px;
        height: 24px;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

      }

      .file-checked-wrapper {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        width: 100%;
        height: 100%;
        display: none;

        .item_top {
          display: flex;
          position: absolute;
          top: 10px;
          left: 0;
          padding: 0 10px;
          box-sizing: border-box;
          width: 100%;
          align-items: center;
          justify-content: space-between;

          .file-checked {
          }

          .moreBtns {
            display: inline-block;
            height: 19px;
            line-height: 19px;
          }

          .downText {
            display: inline-block;
            margin-right: 40px;
          }
        }

      }

      .file-checked-wrapper.checked {
        display: block;
      }
    }

    .file_item.checked {
      background-color: #e3f3ee;
    }
  }
}


</style>
